#coding:utf-8
import os
import re
import datetime
from xml.sax.saxutils import escape
from django.core.management.base import BaseCommand
from django.db.models import Q, Count
from lovewith.settings import ROOT, SITE_URL
from lovewith.utils.tools import my_iterator
from lovewith.share.models import Post, Attachment


class Command(BaseCommand):
    #获取tag搜索结果
    def get_tag_search_result(self, tag, baidu_tag):
        #保存全部帖子id
        share_post_ids = []
        tag_xml_data = []

        attach_filter_data = Attachment.objects.filter(TagAttach__tagname__icontains=tag).order_by('-id')
        for attach in attach_filter_data:
            if not attach.share_post.id in share_post_ids:
                share_post_ids.append(attach.share_post_id)
                onepost_xml_data = self.get_onepost_xml_data(attach.share_post, baidu_tag, fix_cover=attach.path)

                tag_xml_data.extend(onepost_xml_data)

        return tag_xml_data

    #获取商品关键词搜索结果cl
    def get_goods_search_result(self, good_tag, baidu_tag):
        #保存全部帖子id
        share_post_ids = []
        goods_xml_data = []

        attach_filter_data = Attachment.objects.filter(GoodsAttach__tagname__icontains=good_tag).order_by('-id')

        for attach in my_iterator(attach_filter_data):
            if not attach.share_post.id in share_post_ids:
                share_post_ids.append(attach.share_post_id)
                onepost_xml_data = self.get_onepost_xml_data(attach.share_post, baidu_tag, fix_cover=attach.path)

                goods_xml_data.extend(onepost_xml_data)

        return goods_xml_data

    #JSON To XMl
    def to_xml(self, xml_data):
        img_xml_data = ['<pic>']

        if xml_data['pic_desc'] == '':
            xml_data['pic_desc'] = xml_data['pic_title']

        for tag in xml_data:
            data = escape(xml_data[tag])
            data = ''.join(data.split())

            img_xml_data.append('<%s>%s</%s>' % (tag, data, tag))
        img_xml_data.append('</pic>')

        return img_xml_data

    #获取单个帖子的xml数据
    def get_onepost_xml_data(self, post_data, baidu_tag, fix_cover=None):
        post_xml_data = []
        index = 2
        post_desc = re.compile(r'<[^>]+>', re.S).sub('', post_data.content)
        post_desc = escape(post_desc.replace('&amp;nbsp;', ''))
        post_desc = re.compile(r'&[^;]*?;', re.S).sub('', post_desc)
        pic_desc = post_desc
        post_title = re.compile(r'&[^;]*?;', re.S).sub('', post_data.title)
        post_title = escape(post_title.replace('&', ' '))

        if len(post_title) > 15:
            post_title = '%s...' % post_title[0:12]

        if len(post_desc) > 90:
            post_desc = '%s...' % post_desc[0:90]

        if len(post_desc) > 15:
            pic_desc = '%s...' % post_desc[0:12]

        post_xml_data.append('<set><set_title>%s</set_title>' % post_title)

        if post_desc == '':
            post_xml_data.append('<set_desc>%s</set_desc>' % post_title)
        else:
            post_xml_data.append('<set_desc>%s</set_desc>' % post_desc)

        post_xml_data.append('<set_column>婚嫁</set_column><set_tag>%s</set_tag>' % baidu_tag)

        #获取帖子全部图片
        img_filter_data = Attachment.objects.filter(share_post_id=post_data.id, is_delete=False).order_by(
            '-is_cover')
        for img in my_iterator(img_filter_data):
            pic_url = '%s!650' % img.path
            pic_from_url = '%sshare/detail/all/%s/#m%s' % (SITE_URL, post_data.id, img.id)

            pic_seq = str(index)
            if fix_cover and img.path == fix_cover:
                pic_seq = '1'
            elif img.is_cover:
                pic_seq = '1'

            img_xml_data = self.to_xml({
                'pic_url': pic_url,
                'pic_from_url': pic_from_url,
                'pic_title': post_title,
                'pic_desc': pic_desc,
                'pic_seq': pic_seq
            })

            index += 1
            post_xml_data.extend(img_xml_data)

        post_xml_data.append('</set>')

        return post_xml_data

    #根据获取post_data的图片列表组
    def get_xml_data_by_post_data(self, post_filter_data, baidu_tag, start_date, end_date):
        posts_xml_data = []
        #按日期筛选
        if start_date:
            post_filter_data = post_filter_data.filter(post_date__gte=start_date)
        if end_date:
            post_filter_data = post_filter_data.filter(post_date__lte=end_date)

        #去除被删除的帖子,按时间倒序
        post_filter_data = post_filter_data.filter(is_delete=False).order_by('-id')
        for post_data in my_iterator(post_filter_data):
            onepost_xml_data = self.get_onepost_xml_data(post_data, baidu_tag)

            posts_xml_data.extend(onepost_xml_data)

        return posts_xml_data

    #sitemap
    def handle(self, *args, **options):
        #rss文件根路径
        xml_path = os.path.join(ROOT, 'static/sitemap').replace('\\', '/')

        #需要生成xml文件的关键词
        target_keyword = [
            {'name': 'tag', 'bd_tag': '结婚蛋糕', 'value': '蛋糕'},
            {'name': 'tag', 'bd_tag': '请柬', 'value': '请柬'},
            {'name': 'tag', 'bd_tag': '喜糖盒', 'value': '喜糖盒'},
            {'name': 'tag', 'bd_tag': '手捧花', 'value': '手捧花'},
            {'name': 'tag', 'bd_tag': '婚礼甜品', 'value': '甜品'},
            {'name': 'tag', 'bd_tag': '户外婚礼', 'value': '户外'},
            {'name': 'tag', 'bd_tag': '海滩婚礼', 'value': '海滩'},
            {'name': 'tag', 'bd_tag': '婚礼跟拍', 'value': '跟拍'},
            {'name': 'tag', 'bd_tag': '蕾丝', 'value': '蕾丝'},
            {'name': 'tag', 'bd_tag': '头饰', 'value': '头饰'},
            {'name': 'tag', 'bd_tag': '婚鞋', 'value': '婚鞋'},
            {'name': 'tag', 'bd_tag': '主题婚礼', 'value': '主题婚礼'},
            {'name': 'cate', 'bd_tag': '真实婚礼', 'value': 11},
            {'name': 'cate', 'bd_tag': '婚礼布置', 'value': 2},
            {'name': 'cate', 'bd_tag': '婚纱摄影', 'value': 3},
            {'name': 'cate', 'bd_tag': 'DIY创意', 'value': 1},
            {'name': 'cate', 'bd_tag': '婚纱礼服', 'value': 4},
            {'name': 'cate', 'bd_tag': '配饰', 'value': 12},
            {'name': 'cate', 'bd_tag': '新房布置', 'value': 6},
            {'name': 'cate', 'bd_tag': '蜜月旅行', 'value': 9},
            {'name': 'cate', 'bd_tag': '婚戒首饰', 'value': 5},
            {'name': 'cate', 'bd_tag': '新娘妆', 'value': 7},
            {'name': 'keyword', 'bd_tag': '婚礼灵感', 'value': '婚礼灵感'},
            {'name': 'goods', 'bd_tag': '婚礼道具', 'value': '婚礼装饰'}
        ]

        start_date = datetime.date(2014, 5, 22)
        end_date = None

        diff_days = (datetime.date.today() - start_date).days

        if diff_days <= 0:
            #5.22前返回截至2014.2.10的数据
            start_date = datetime.date(2011, 5, 1)
            end_date = datetime.date(2014, 2, 10)
        else:
            #5.22之后按时间往后推3天返回数据
            start_date = datetime.date(2014, 2, 10) + datetime.timedelta(days=(diff_days - 1) * 3)
            end_date = start_date + datetime.timedelta(days=7)

        xml_file = os.path.join(xml_path, 'bd_image.xml')

        #清空文件
        img_xml_str = '<?xml version="1.0" encoding="utf-8" ?><data_v1><update_period_day>1</update_period_day>'
        xml_object = open(xml_file, 'w')
        xml_object.write(img_xml_str)
        xml_object.close()

        file_xml_data = []
        for item in target_keyword:
            if item['name'] == 'tag':
                #标签搜索结果
                tag_xml_data = self.get_tag_search_result(item['value'], item['bd_tag'])
                file_xml_data.extend(tag_xml_data)

            if item['name'] == 'goods':
                #商品搜索结果
                goods_xml_data = self.get_goods_search_result(item['value'], item['bd_tag'])
                file_xml_data.extend(goods_xml_data)

            if item['name'] == 'cate':
                #类目结果
                post_filter_data = Post.objects.filter(cate__id=item['value'])
                key_xml_data = self.get_xml_data_by_post_data(post_filter_data, item['bd_tag'], start_date, end_date)

                file_xml_data.extend(key_xml_data)

            if item['name'] == 'keyword':
                #关键词结果
                post_filter_data = Post.objects.filter(
                    Q(title__icontains=item['value']) | Q(content__icontains=item['value']))
                key_xml_data = self.get_xml_data_by_post_data(post_filter_data, item['bd_tag'], start_date, end_date)

                file_xml_data.extend(key_xml_data)

            #如果数字长度超过5000则先保存一次
            if len(file_xml_data) > 5000:
                #写文件
                xml_object = open(xml_file, 'a+')
                xml_object.write('%s' % ''.join(file_xml_data))
                xml_object.close()

                file_xml_data = []

        #写文件
        xml_object = open(xml_file, 'a+')
        xml_object.write('%s</data_v1>' % ''.join(file_xml_data))
        xml_object.close()




